package com.zgq.share.ui;

import java.util.concurrent.atomic.AtomicInteger;

import com.zgq.share.widget.ShareTabIndicator;
import com.zgq.share.ui.R;

import android.app.TabActivity;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Window;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;

public class HomeActivity extends TabActivity implements OnTabChangeListener {
	
	private static final String PKG_NAME = "com.zgq.share.ui";
	
	private static final int TAB_INDEX_MAX = 3;
	
	private AtomicInteger lastTabIndex = new AtomicInteger(0);
	
	private static int ICONS;
	
	static {
		ICONS = R.drawable.share_tab_icons;
	} 
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
        
        init();
    }
    
	private void init() {

		String[] tabLabels = getResources().getStringArray(
				R.array.tab_name);
		String[] tabActs = getResources().getStringArray(
				R.array.tab_act);

		setDefaultTab(0);

		TabHost tabs = getTabHost();

		for (int i = 0; i < tabLabels.length; i++) {
			TabHost.TabSpec tab = tabs.newTabSpec(tabLabels[i]);

			ComponentName oneActivity = new ComponentName(PKG_NAME,
						"com.zgq.share.ui." + tabActs[i]);
			Intent intent = new Intent().setComponent(oneActivity);
			intent.putExtras(intent);

			tab.setContent(intent);
			tab.setIndicator(new ShareTabIndicator(this, tabLabels[i],
					ICONS));

			tabs.addTab(tab);
		}
		tabs.setOnTabChangedListener(this);
		changeTextEffect(tabs);
	}
	
	private void changeTextEffect(TabHost tabs) {
		for (int i = 0; i < TAB_INDEX_MAX; i++) {
			try {
				ShareTabIndicator areaDetailsTab = (ShareTabIndicator) tabs
						.getTabWidget().getChildAt(i);
				RelativeLayout lay = (RelativeLayout) areaDetailsTab.getChildAt(0);
				TextView tv = (TextView) lay.getChildAt(0);
				if (i == getLastTabIndex()) {
					tv.setTextColor(Color.BLACK);
				} else {
					tv.setTextColor(Color.WHITE);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public int getLastTabIndex() {
		return lastTabIndex.get();
	}

	public void setLastTabIndex(int lastTabIndex) {
		this.lastTabIndex.set(lastTabIndex);
	}

	@Override
	public void onTabChanged(String tabId) {
		TabHost tabs = getTabHost();
		int cur = tabs.getCurrentTab();
		setLastTabIndex(cur);
		changeTextEffect(tabs);
	}
}